import fs from "node:fs/promises";

class DirName {
  constructor(path) {
    this.path = path;
    this.type = undefined;
    this.children = [];
  }
}

class FsExtends {
  // 递归删除非空目录
  static async rmNoEmptyDir(path) {
    await fs.access(path);
    const filedirs = await fs.readdir(path);

    for (const filedif of filedirs) {
      let fileStat = await fs.stat(path + "/" + filedif);
      if (fileStat.isFile()) {
        await fs.unlink(path + "/" + filedif);
      } else if (fileStat.isDirectory()) {
        await this.rmNoEmptyDir(path + "/" + filedif);
      }
    }

    await fs.rmdir(path);
  }

  // 清空目录，但不删除目录本身
  static async emptyDir(path) {
    await this.rmNoEmptyDir(path);
    await fs.mkdir(path);
  }

  // 读取目录，返回一个包含所有文件和子目录的树状结构
  static async readDeepDir(path) {
    let res = new DirName(path);
    let fileStat = await fs.stat(path);

    if (fileStat.isFile()) {
      res.type = "file";
      res.children = null;
    } else if (fileStat.isDirectory()) {
      res.type = "dir";
      let dirs = await fs.readdir(path);

      if (dirs.length === 0) {
        res.children = null;
      } else {
        let childrenPromises = dirs.map(async (dir) => {
          let child = await readDeepDir(path + "/" + dir);
          return child;
        });
        res.children = await Promise.all(childrenPromises);
      }
    }

    return res;
  }
}

// 继承fs模块的原型链，这样就可以直接使用fs的所有方法了
Object.setPrototypeOf(FsExtends, fs);

export { FsExtends };
